package com.example.flowermall.controller;

import com.example.flowermall.entity.Result;
import com.example.flowermall.entity.UserAddress;
import com.example.flowermall.service.IUserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
 * <p>
 *  地址控制器
 * </p>
 *
 * @author xiaoman
 * @since 2023-09-04
 */
@RestController
@RequestMapping("/userAddress")
public class UserAddressController {
    @Autowired
    IUserAddressService userAddressService;

    //模糊查询
    @GetMapping("/lists")
    public Result selectUserAddress(@RequestParam("id") Integer id){
        List<UserAddress> listByUserId = userAddressService.getListByUserId(id);
        Result result=Result.success();
        result.put("data",listByUserId);
        return result;
    }
    @PostMapping("/add")
    public Result insertUserAddress(@RequestBody UserAddress userAddress){
        Integer count = userAddressService.countByUserId(userAddress.getUserId());
        if(count>=3){
            return Result.error("增加收货地址失败！您的收货地址的数量已经达到上限（" + 3 + "条）！");
        }

        userAddressService.save(userAddress);
        return  Result.success("添加成功");
    }
    @GetMapping("/info")
    public Result getUserAddressById(@RequestParam("id")Integer id){
        UserAddress addressById = userAddressService.getUserAddressById(id);
        Result result=Result.success();
        result.put("data",addressById);
        return result;
    }
    @PutMapping("/update")
    public Result updateUserAddress(@RequestBody UserAddress userAddress){
        userAddressService.updateUserAddress(userAddress);
        return Result.success(userAddress);
    }
    @DeleteMapping("/{id}")
    public Result deleteUserAddress(@PathVariable("id")Integer id) {
        userAddressService.deleteById(id);
        return Result.success("删除成功");
    }

    @PutMapping("/updateCommonAdd")
    public Result updateCommonAdd(@RequestBody UserAddress userAddress){
        List<UserAddress> listByUserId = userAddressService.getListByUserId(userAddress.getUserId());
        for(int i=0;i<listByUserId.size();i++){
            if(listByUserId.get(i).getAddressId()==userAddress.getAddressId()){
                userAddress.setCommonAddress(1);
                userAddressService.updateUserAddress(userAddress);
            }
            else {
                listByUserId.get(i).setCommonAddress(0);
                userAddressService.updateUserAddress(listByUserId.get(i));
            }
        }
        return Result.success("修改成功");
    }
}
